package com.sky.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.dto.AddressBookDto;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    // 新增地址
    @Override
    public void addAddressBook(AddressBookDto addressBookDto) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressBookDto,addressBook);
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        save(addressBook);
    }

    // 查询默认地址
    @Override
    public AddressBook selectByIsDefault() {
        return getOne(Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getIsDefault,AddressBook.ISDEFAULT));
    }

    // 修改默认地址
    @Override
    @Transactional
    public void updateIsDefault(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        // ToDo bug:设置其他地址为默认值时，并没有将原默认地址的改为0
        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);
    }


}
